<script setup>
import { ref,computed } from 'vue'

// 要渲染的数据
const goods = ref([
  {
    id: 1,
    goods_name: '华为手环',
    goods_price: 169,
    goods_num: 1,
    checked: false,
  },
  {
    id: 2,
    goods_name: '索尼耳机',
    goods_price: 163,
    goods_num: 1,
    checked: false,
  },
  {
    id: 3,
    goods_name: '小米汽车',
    goods_price: 1890,
    goods_num: 1,
    checked: false,
  },
  {
    id: 4,
    goods_name: 'iPhone14',
    goods_price: 1699,
    goods_num: 1,
    checked: false,
  },
])

// 计算属性
// 全选
const isSelectAll = computed({
  get() {
    return goods.value.every((item) => item.checked);
  },
  set(newValue) {
    goods.value.forEach((item) => (item.checked = newValue));
  }
})


// 总共的商品数量
const totalNum = computed(() => goods.value.length);

// 已选择的商品数量
const selectedNum = computed(() => {
return goods.value.filter((item) => item.checked).length;
});

// 合计
const total = computed(() => {
 let totalPrice = 0;
 for(let good of goods.value) {
  if(good.checked) {
    totalPrice += good.goods_price * good.goods_num;
  }
 }
 return totalPrice;
})

// 方法
// 删除某个商品
const deleteGood = (id) => {
  goods.value = goods.value.filter((item) => item.id !== id);
}

// 删除选中的商品
const deleteChoosedGood = () => {
  goods.value = goods.value.filter((item) => !item.checked);
}
</script>

<template>
  <div id="app">
    <div id="shoppingcart">
      <table>
        <!-- 第一行 标题行 -->
        <tr>
          <td>
            <input type="checkbox" v-model="isSelectAll"/>
            全选
          </td>
          <td>商品</td>
          <td>单价(元)</td>
          <td>数量</td>
          <td>小记(元)</td>
          <td>操作</td>
        </tr>
        <!-- 第二行 内容行 -->
        <tr v-for="item in goods" :key="item.id">
          <td>
            <input type="checkbox" v-model="item.checked"/>
          </td>
          <td>{{ item.goods_name }}</td>
          <td>{{ item.goods_price }}</td>
          <td>
            <button @click="item.goods_num > 0?item.goods_num--:0">-</button>
            <input type="text" v-model="item.goods_num" class="ipt"/>
            <button @click="item.goods_num++">+</button>
          </td>
          <td>{{ item.goods_price * item.goods_num }}</td>
          <td><button class="danger" @click="deleteGood(item.id)">删除</button></td>
        </tr>
      </table>
      <!-- footer部分 -->
      <footer class="footer">
        <div class="footer-left">
          <input type="checkbox" v-model="isSelectAll"/>
          <span>全选</span>
          <a @click="deleteChoosedGood">删除所选中的商品</a>
          <span>共{{totalNum}}件商品,已选择{{selectedNum}}件</span>
        </div>
        <div class="footer-right">
          <div>合计(不含运费): <span>¥ {{ total }}</span></div>
          <button>去结算</button>
        </div>
      </footer>
    </div>
  </div>
</template>

<style scoped>
@import './assets/shopping-cart.css';
</style>
